package org.qb.mapreduce.reduceJoinDemo;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;

import java.io.IOException;

public class ReduceJoinMapper extends Mapper<LongWritable, Text,Text,ReduceJoinBean> {

    private String fileName;
    private final Text outK = new Text();
    private final ReduceJoinBean outV = new ReduceJoinBean();

    @Override
    protected void setup(Mapper<LongWritable, Text, Text, ReduceJoinBean>.Context context) throws IOException, InterruptedException {

        //初始化方法，
        // 两个文件 other.txt pd.txt
        InputSplit inputSplit = context.getInputSplit();
        FileSplit fileSplit = (FileSplit) inputSplit;
        fileName = fileSplit.getPath().getName();
    }

    @Override
    protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, ReduceJoinBean>.Context context) throws IOException, InterruptedException {

        //获取第一行，
        // 并且分割
        String[] split = value.toString().split("\t");

        //判断哪一个文件，进行入值
        if (fileName.contains("order")){

            outK.set(split[1]);
            outV.setOrderId(split[0]);
            outV.setpId(split[1]);
            outV.setCount(Integer.parseInt(split[2]));
            outV.setProductName("");
            outV.setFlag("order");

        }else {

            outK.set(split[0]);
            outV.setOrderId("");
            outV.setpId(split[0]);
            outV.setCount(0);
            outV.setProductName(split[1]);
            outV.setFlag("pd");
        }

        context.write(outK,outV);
    }
}
